package cn.com.colasoft.netty.helloworld;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.ReferenceCountUtil;

/**
 * Created by lizhitao on 2017/6/7.
 */
public class ServerHandler extends ChannelHandlerAdapter {
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        try {
            String request = (String) msg;
            //ByteBuf buf = (ByteBuf) msg;
            //byte[] bytes = new byte[buf.readableBytes()];
            //buf.readBytes(bytes);
            //String s = new String(bytes, "UTF-8");
            System.out.println("Server:" + request);


            // 写给客户端,这里不能直接写字符串,必须转为ByteBuf
            ctx.writeAndFlush(Unpooled.copiedBuffer("这是回写给你的信息".getBytes("UTF-8")))
            .addListener(ChannelFutureListener.CLOSE);// 数据已经写完,服务端断开与客户端的连接,服务端断开,但是服务端进程还在

        }finally {
            // 这里其实是不需要释放的,因为上面有ctx.write()方法,只要有write方法,
            // 这是内部的一个优化
            // ReferenceCountUtil.release(msg);
        }
    }
}
